package com.kehutong.contact.util;

import com.kehutong.contact.entity.Resident;
import org.coraframework.util.Objects;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 住户标签工具类
 *
 * @author: liukunlong
 * @date: 2021-02-25 20:57
 */
public class ResidentTagUtil {

    /**
     * 汇总标签标记数量及所在维度的百分比
     * @param tagList 标签集合
     * @param residentList 住户集合
     * @return
     */
    @SuppressWarnings("unchecked")
	public static List<Map<String, Object>> sumTags(List<Map<String,Object>> tagList, List<Resident> residentList) {
        List<Map<String, Object>> result = new ArrayList<>();

        if(Objects.isEmpty(tagList) || Objects.isEmpty(residentList)){
            return result;
        }
        //二级标签编号与标记数量的映射
        Map<String, Integer> tagIdToNumberMapping = new HashMap<>();

        //汇总所有标签标记数量
        residentList.forEach(resident -> {
            List<String> tagIds = resident.getTagIds();
            for (String tagId : tagIds) {
                if (tagIdToNumberMapping.containsKey(tagId)) {//若map中已经存在
                    tagIdToNumberMapping.put(tagId, tagIdToNumberMapping.get(tagId) + 1);//自动拆箱
                } else {
                    tagIdToNumberMapping.put(tagId, 1);
                }
            }
        });
        //生成标签相关数据
        tagList.forEach(tagOne -> {
            Map<String, Object> tagOneMap = new LinkedHashMap<>();
            tagOneMap.put("tagNo", tagOne.get("tagNo"));
            tagOneMap.put("tagName", tagOne.get("tagName"));
            List<Map<String, Object>> childList = (List<Map<String, Object>>) tagOne.get("childList");
            if (Objects.nonEmpty(childList)) {
                List<Map<String, Object>> childListMap = new ArrayList<>();
                childList.forEach(tagTwo -> {
                    Integer amount=tagIdToNumberMapping.get(tagTwo.get("tagNo"));
                    if(Objects.nonNull(amount)){
                        Map<String, Object> tagTwoMap = new LinkedHashMap<>();
                        tagTwoMap.put("tagNo", tagTwo.get("tagNo"));
                        tagTwoMap.put("tagName", tagTwo.get("tagName"));
                        tagTwoMap.put("amount",amount);
                        childListMap.add(tagTwoMap);
                    }
                });
                int sum = childListMap.stream().mapToInt(map -> (int) map.get("amount")).sum();
                childListMap.forEach(tagTwoMap -> {
                    int amount= (int) tagTwoMap.get("amount");
                    if(amount==0){
                        tagTwoMap.put("radio","0.00%");
                    }else{
                        tagTwoMap.put("radio", getPercent((int) tagTwoMap.get("amount"), sum));
                    }
                });

                tagOneMap.put("childList", childListMap);
            }
            result.add(tagOneMap);
        });
        return result;
    }

    /**
     * 计算百分比
     *
     * @param x
     * @param y
     * @return
     */
    private static String getPercent(int x, int y) {
        double d1 = x * 1.0;
        double d2 = y * 1.0;
        // 设置保留几位小数， “.”后面几个零就保留几位小数，这里设置保留四位小数
        DecimalFormat decimalFormat = new DecimalFormat("#,##0.00%");
        return decimalFormat.format(d1 / d2);
    }
    /**
     * 渲染符合员工的标签信息
     * 数据库保存格式:111;222,3333;444(不同客户之间以“,”分隔,不同客户之间以“;”分隔)系统会自动转成以逗号分隔的集合
     * 1.如果没有员工则显示所有员工标签并且去重复
     * 2.如果有员工则显示符合条件员工的标签并且去重复
     *
     * @param userIds      员工编号
     * @param residentList 住户集合数据
     */
    public static void renderTags(List<String> userIds, List<Resident> residentList) {
        if (Objects.nonEmpty(residentList)) {
            residentList.forEach(item -> {
                renderTag(userIds, item);
            });
        }
    }

    /**
     * 删除标签及根基
     * @param userId 用户编号
     * @param resident 住户信息
     */
    public static void removeTags(String userId, Resident resident) {
        if (Objects.nonNull(resident) && Objects.nonEmpty(userId)) {
            List<String> dbTagUsers = resident.getTagUsers();
            List<String> dbTagIds = resident.getTagIds();
            List<String> dbTagNames = resident.getTagNames();
            //没有标签直接跳出
            if (Objects.isEmpty(dbTagUsers) || Objects.isEmpty(dbTagIds) || Objects.isEmpty(dbTagNames)) {
                return;
            }
            if (dbTagUsers.contains(userId)) {
                int tagIndex = dbTagUsers.indexOf(userId);
                dbTagUsers.remove(tagIndex);
                dbTagIds.remove(tagIndex);
                dbTagNames.remove(tagIndex);
            }

        }
    }

    /**
     * 渲染住户的标签信息
     * 数据库保存格式:111;222,3333;444(不同客户之间以“,”分隔,不同客户之间以“;”分隔)系统会自动转成以逗号分隔的集合
     *
     * @param userIds  员工编号
     * @param resident 住户信息
     */
    public static void renderTag(List<String> userIds, Resident resident) {
        if (Objects.isNull(resident)) {
            return;
        }
        Set<String> tagIds = new LinkedHashSet<>();
        Set<String> tagNames = new LinkedHashSet<>();
        List<String> tagUsersList = resident.getTagUsers();
        List<String> tagIdsList = resident.getTagIds();
        List<String> tagNamesList = resident.getTagNames();
        //没有标签直接跳出
        if (Objects.isEmpty(tagUsersList) || Objects.isEmpty(tagIdsList) || Objects.isEmpty(tagNamesList)) {
            return;
        }
        for (int i = 0, len = tagUsersList.size(); i < len; i++) {
            String tagUser = tagUsersList.get(i);
            String tagIdsStr = tagIdsList.get(i);
            String tagNamesStr = tagNamesList.get(i);
            //若没有员工标志结合则合并当前记录所有人打的标签信息,否则显示符合条件的标签信息
            if (Objects.nonEmpty(userIds)) {
                if (userIds.contains(tagUser)) {
                    Set<String> tagIdSet = Arrays.stream(tagIdsStr.split(";")).collect(Collectors.toSet());
                    tagIds.addAll(tagIdSet);
                    Set<String> tagNameSet = Arrays.stream(tagNamesStr.split(";")).collect(Collectors.toSet());
                    tagNames.addAll(tagNameSet);
                }
            } else {
                Set<String> tagIdSet = Arrays.stream(tagIdsStr.split(";")).collect(Collectors.toSet());
                tagIds.addAll(tagIdSet);

                Set<String> tagNameSet = Arrays.stream(tagNamesStr.split(";")).collect(Collectors.toSet());
                tagNames.addAll(tagNameSet);
            }

        }
        resident.setTagIds(new ArrayList<>(tagIds));
        resident.setTagNames(new ArrayList<>(tagNames));
    }


    /**
     * 设置住户信息标签
     * 数据库保存格式:111;222,3333;444(不同客户之间以“,”分隔,不同客户之间以“;”分隔)系统会自动转成以逗号分隔的集合
     * 1.当前员工没有设置过标签
     * 2.当前员工原来设置过标签,进行覆盖更新
     * @param userId   用户编号
     * @param tagIds   标签编号集合
     * @param tagNames 标签名称集合
     * @param resident 住户对象
     */
    public static void setTag(String userId, List<String> tagIds, List<String> tagNames, Resident resident) {

        if (Objects.isEmpty(userId) || Objects.isEmpty(tagIds) || Objects.isEmpty(tagNames) || Objects.isNull(resident)) {
            return;
        }
        //标签维护
        List<String> dbTagUsers = resident.getTagUsers();
        if(Objects.isEmpty(dbTagUsers)){
            dbTagUsers=new ArrayList<>();
        }
        List<String> dbTagIds = resident.getTagIds();
        if(Objects.isEmpty(dbTagIds)){
            dbTagIds=new ArrayList<>();
        }
        List<String> dbTagNames = resident.getTagNames();
        if(Objects.isEmpty(dbTagNames)){
            dbTagNames=new ArrayList<>();
        }
        String tagIdsStr = tagIds.stream().map(String::valueOf).collect(Collectors.joining(";"));
        String tagNamesStr = tagNames.stream().map(String::valueOf).collect(Collectors.joining(";"));
        if (dbTagUsers.contains(userId)) {
            for (int i = 0, len = dbTagUsers.size(); i < len; i++) {
                if (Objects.equal(dbTagUsers.get(i), userId)) {
                    dbTagIds.set(i, tagIdsStr);
                    dbTagNames.set(i, tagNamesStr);
                }
            }
        } else {
            dbTagUsers.add(userId);
            dbTagIds.add(tagIdsStr);
            dbTagNames.add(tagNamesStr);
        }


        resident.setTagUsers(dbTagUsers);
        resident.setTagIds(dbTagIds);
        resident.setTagNames(dbTagNames);
    }
}
